<?php

namespace app\common\controller;

use app\BaseController;
use app\common\auth\AdminAuth;
use app\common\core\HtmlPassage;
use app\common\model\AdminLog;
use app\common\model\AuthRule;
use app\common\traits\Backend;
use think\facade\Db;
use think\facade\Env;
use think\facade\Lang;

class BaseAdminController extends BaseController
{
    /**
     * 无需登录的方法,同时也就不需要鉴权了.
     *
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录.
     *
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 布局模板
     *
     * @var string
     */
    protected $layout = 'default';



    protected $index_get_data = false;// index方法是否开启数据获取

    /**
     * 权限控制类.
     *
     * @var Auth
     */
    protected $auth = null;//


    protected $relationSearch = false;// 是否开启模型关联查询


    protected $editField = ['*'];// 编辑字段

    protected $addField = ['*'];// 新增字段

    /**
     * 模型对象
     *
     * @var \think\Model
     */
    protected $model = null;
    protected $addons = null;
    protected $module = null;
    protected $controller = null;
    protected $action = null;

    use Backend;
    public function initialize()
    {
        parent::initialize();
        $this->get_path();
        $jsName = $this->addons?('addons/'.$this->addons.'/'.$this->module.'/'.str_replace('.','/',$this->controller)):$this->module.'/'.str_replace('.','/',$this->controller);
        $upload = config('upload');
        $theme_color = Db::name('config')->where('name','theme')->find();
        $ntheme_color =[
            'theme_color'=>'#409eff',
            'horizontal_background'=>'#fff',
            'vertical_background'=>'#fff',
        ];
        if(!empty($theme_color)){
            if(!empty($theme_color['value'])){
                if(is_string($theme_color['value'])){
                    $theme_color = json_decode($theme_color['value'],true);
                }else{
                    $theme_color = $theme_color['value'];
                }
            }else{
                $theme_color = $ntheme_color;
            }
        }else{
            $theme_color =$ntheme_color;
        }
        $site = Db::name('config')->where('name','site_config')->find();
        if(!empty($site)){
            $site_config = $site['value'];
            if(is_string($site_config)){
                $site_config = json_decode($site_config,true);
            }
        }else{
            $site_config = [
                'name'=>'沐雨快速开发框架',
                'logo'=>'/static/image/logo.jpg'
            ];
        }
        $referer = session('referer');
        $addtabs = $this->request->param('addtabs');
        if($addtabs&&$this->request->isGet()&&!$this->request->isAjax()){
            if($this->addons){
                $res = AuthRule::where('module',$this->addons.'/'.$this->module)
                    ->where('route',"LIKE",$this->controller.'/'.$this->action.'%')
                    ->find();
            }else{
                $res = AuthRule::where('module',$this->module)
                    ->where('route',"LIKE",$this->controller.'/'.$this->action.'%')
                    ->find();
            }
            if(!empty($res)){
                $referer = $res->toArray();
                $referer['title'] = __($referer['title']);
                $referer['module'] = get_app_map($referer['module']);
            }
            session('referer', $referer);
        }
        $upload['uploadurl'] = '/'.get_app_map('admin').'/'.$upload['uploadurl'];
        $upload['show_file_url'] = '/'.get_app_map('admin').'/general.attachment/index';
        $config = [
            'time'=>time(),
            'de_bug'=>Env::get('APP_DEBUG',false)?1:0,
            'jsname'=>strtolower($jsName),
            'actionname'=>$this->action,
            'version'=>time(),
            'config_array'=>[
                'addons'=>$this->addons,
                'module'=>$this->addons?$this->module:get_app_map($this->module),
                'controller'=>strtolower($this->controller),
                'action'=>strpos($this->action,'.html')===false?$this->action:str_replace('.html','',$this->action),
            ],
            'upload'=>$upload,
            'theme'=>$theme_color,
            'site_obj'=>$site_config,
            'sub_url'=>$this->request->url(),
            'referer'=>$referer
        ];
//        echo "<pre>";
//        print_r($config);
//        exit;
        $addHtml = HtmlPassage::instance()->getAddHtml();
        if(!empty($addHtml)){
            $config['addHtml'] = $addHtml;
        }else{
            $config['addHtml'] = [];
        }
        $this->view->assign('config', $config);
        $this->auth = AdminAuth::instance();

        // 检测是否需要验证登录
        if(!in_array('*', $this->noNeedLogin)&&!in_array($this->request->action(), $this->noNeedLogin)){
            if(!$this->auth->isLogin()){
                $url = url('login', [], false)->build();
//                $url = str_replace('.html','',strtolower($url->build()));
                return $this->redirect($url);
            }
            if(!empty($this->noNeedRight)&&!in_array('*', $this->noNeedRight)&&!in_array($this->request->action(), $this->noNeedRight)){
                /// todo 权限验证
            }
        }
        if(empty($this->addons)){
            $rule = Db::name('auth_rule')->where('module',$this->module)
                ->where('route',"LIKE",$this->controller.'/'.$this->action.'%')
                ->find();
        }else{
            $rule = Db::name('auth_rule')->where('module',$this->addons.'/'.$this->module)
                ->where('route',"LIKE",$this->controller.'/'.$this->action.'%')
                ->find();
        }
        if(!empty($rule)){
            $title = __($rule['title']);
            AdminLog::record($title);
        }
    }
    public function get_path()
    {
        $url = $this->request->baseUrl();
        $array = explode('/', $url);
        $array = array_filter($array);
        $array = array_values($array);
        if(isset($array[0])&&$array[0]=='addons'){
            $this->addons = isset($array[1])?$array[1]:'index';
            $this->module = isset($array[2])?$array[2]:'index';
            $this->controller = isset($array[3])?$array[3]:'index';
            $this->action = isset($array[4])?$array[4]:'index';

        }else{
            $this->module = get_app_map(isset($array[0])?$array[0]:'index',true);
            $this->controller = isset($array[1])?$array[1]:'index';
            $this->action =isset($array[2])?$array[2]:'index';
        }
        $this->action = str_replace('.html','',$this->action);
    }
    /**
     * 加载语言文件.
     *
     * @param  string  $name
     */
    protected function loadlang($name)
    {
        if (strpos($name, '.')) {
            $_arr = explode('.', $name);
            if (count($_arr) > 1) {
                $path = '';
                foreach ($_arr as $v){
                    $path .= '/'.parseName($v);
                }
                $path = ltrim($path,'/');
            } else {
                $path = strtolower($name);
            }
        } else {
            $path = parseName($name);
        }
        Lang::load(app()->getAppPath().'/lang/'.Lang::getLangset().'/'.$path.'.php');
    }
    /**
     * 渲染配置信息.
     *
     * @param  mixed  $name  键名或数组
     * @param  mixed  $value  值
     */
    protected function assignconfig($name, $value = '')
    {
        $this->view->config = array_merge($this->view->config ? $this->view->config : [],
            is_array($name) ? $name : [$name => $value]);
    }
}